package com.tbvtc.agriculturalcreditchainserver2025.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageCompressUtil {

    /**
     * 压缩图片
     * @param file 原始文件
     * @param targetWidth 目标宽度
     * @param targetHeight 目标高度
     * @param quality 压缩质量（0.0 - 1.0，值越小压缩率越高）
     * @return 压缩后的字节数组
     * @throws IOException 异常
     */
    public static byte[] compressImageByFile(MultipartFile file, int targetWidth, int targetHeight, float quality) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 对图片进行缩放、设置压缩质量
        Thumbnails.of(file.getInputStream())
                .size(targetWidth, targetHeight)
                .outputQuality(quality)
                .toOutputStream(outputStream);
        return outputStream.toByteArray();
    }

    public static byte[] compressImage(ByteArrayInputStream bytes, int targetWidth, int targetHeight, float quality) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 对图片进行缩放、设置压缩质量
        Thumbnails.of(bytes)
                .size(targetWidth, targetHeight)
                .outputQuality(quality)
                .toOutputStream(outputStream);
        return outputStream.toByteArray();
    }
}